package cn.wolfcode.jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @ClassName JdkTestDemo
 * @Description JDK动态代理
 * @Author xdzhango
 * @Date 2020/5/19 14:45
 **/
public class JdkTestDemo implements InvocationHandler {
    private JdkTest subject;

    public JdkTestDemo(JdkTest subject){
        this.subject = subject;
    }


    /**
     * @Author xdzhango
     * @Description //TODO
     * @Date 15:31
     * @Param proxy 用来绑定实例接口方法
     * @Param method 调用的方法,可以用方法来过滤,得到方法声明类等等
     * @Param args
     * @return java.lang.Object
     **/
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("doSomething")){
            System.out.println("做某些事前的准备");
            Object object = method.invoke(subject,args);
            System.out.println("做某些事后期收尾");
            return object;
        }
        return "调用失败";
    }

    /**
     * 获取被代理接口实例对象
     */
    public JdkTest getProxy() {
        return (JdkTest) Proxy.newProxyInstance(subject.getClass().getClassLoader(), subject.getClass().getInterfaces(), this);
    }

}
